package com.jiankangjin.weixinchannel.services.impl;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.jiankangjin.common.json.jackson.JSONUtil;
import com.jiankangjin.httpclient.HttpClient;
import com.jiankangjin.weixinchannel.config.WeixinConfig;
import com.jiankangjin.weixinchannel.services.INotifyService;
import com.jiankangjin.weixinchannel.statuscode.PaymentStatusCode;
import com.jiankangjin.weixinchannel.util.Sha1Util;
import com.jiankangjin.weixinchannel.util.TenpayHttpClient;

@Service
public class NotifyServiceImpl implements INotifyService {
	private static final transient Log logger = LogFactory.getLog(NotifyServiceImpl.class);


	/**
	 * 交易成功 通知交易系统
	 */
	@Override
	public boolean doPayed(String out_trade_no, String transaction_id,
			String total_fee, String time_end, String trade_state) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("channel_id", "0003");
		params.put("notify_type", "trade_status_sync");
		params.put("out_trade_no", out_trade_no);
		params.put("channel_trade_no", transaction_id);
		params.put("trade_state", PaymentStatusCode.IS_PAYED);
		params.put("trade_time", time_end);
		//params.put("buyer_id", buyer_id);
		//params.put("buyer_email", buyer_email);
		//params.put("seller_id", seller_id);
		//params.put("seller_email", seller_email);
		params.put("total_fee", total_fee);
		params.put("json_str", "");
		params.put("sign", "weixin_sign");
		logger.info("微信通知交易系统:"+params);
		Map<String, Object> transMap = HttpClient.getInstance().doPOSTgetHashMap("/transSystem/notify", params);
		if (transMap == null) {
			logger.error("接入交易系统失败!!!!!!!!!");
			return false;
		}
		logger.info("交易系统返回:"+transMap);
		if("0000".equals(transMap.get("resp_status"))) {
			logger.info("交易系统成功返回,通知交易系统成功");
			return true;
		}
		return false;
	}
	
	/**
	 * 告诉微信已发货
	 */
	@Override
	public boolean doDeliverNotify(String openId, String transId, String outTradeNo){
		try {
			String appId = WeixinConfig.APP_ID;
			String appKey = WeixinConfig.APP_KEY;
			String deliverTimestamp = Sha1Util.getTimeStamp();
			String deliverStatus = "1";
			String deliverMsg = "ok";
			
			SortedMap<String, String> signParams = new TreeMap<String, String>();
			signParams.put("appid", appId);
			signParams.put("appkey", appKey);
			signParams.put("openid", openId);
			signParams.put("transid", transId);
			signParams.put("out_trade_no", outTradeNo);
			signParams.put("deliver_timestamp", deliverTimestamp);
			signParams.put("deliver_status", deliverStatus);
			signParams.put("deliver_msg", deliverMsg);
			String appSignature = Sha1Util.createSHA1Sign(signParams);
			
			Map<String, String> params = new LinkedHashMap<String, String>();
			params.put("appid", appId);
			params.put("openid", openId);
			params.put("transid", transId);
			params.put("out_trade_no", outTradeNo);
			params.put("deliver_timestamp", deliverTimestamp);
			params.put("deliver_status", deliverStatus);
			params.put("deliver_msg", deliverMsg);
			params.put("app_signature", appSignature);
			String signMethod = "sha1";
			params.put("sign_method", signMethod);
			logger.info(params);
			String jsonStr = JSONUtil.toJSON(params);
			logger.info("开始发货：["+jsonStr+"]");
			
			TenpayHttpClient httpClient = new TenpayHttpClient();
	    	String url = WeixinConfig.DELIVER_NOTIFY_URL+WeixinConfig.getAccessToken();
	    	logger.info("发货请求地址：["+url+"]");
	    	boolean resultFlag = httpClient.callHttpPost(url, jsonStr);
	    	if(resultFlag){
	    		logger.info("发货成功！返回报文=["+httpClient.getResContent()+"]");
	    		return true;
	    	}else{
	    		logger.info("发货失败！返回报文=["+httpClient.getResContent()+"]");
	    	}
		} catch (Exception e) {
			logger.error("向微信后台发送收货通知过程中发生异常！");
			e.printStackTrace();
		}
		return false;
	}
}